package io.github.hayeka.a1_threadlocalandmultidatasource.code.filter;

//==================================
//      @Author hayeka
//      @Email hayeka@2980.com
//      @Date 2021/6/16
//==================================

import io.github.hayeka.a1_threadlocalandmultidatasource.code.holder.TenantHolder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;


@Component
@WebFilter(urlPatterns = "/**")
public class TenantHolderFilter extends OncePerRequestFilter {
    //先拿Logger对象
    private static final Logger log = LoggerFactory.getLogger(TenantHolderFilter.class);

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {


        log.info("+++++++++++++请求路径:[=>{}<=]+++请求时间:[{}]++++++++++++++++++++++++", request.getRequestURL(), LocalDateTime.now());
        String host = request.getHeader("Host");
        log.info("处理请求的线程是:[{}],host是:[{}]", Thread.currentThread().getName(), host);
        String tenantCode = host.split("\\.")[0];
        //设置tenant
        TenantHolder.setTenant(tenantCode);
        try {
            chain.doFilter(request, response);
        } catch (Exception e) {
            //异常处理
            log.info("{}", e.getMessage());
        } finally {
            //移除tenant
            TenantHolder.removeTenant();
            log.info("+++++++++++++请求路径:[=>{}<=]+++请求时间:[{}]++++++++++++++++++++++++", request.getRequestURL(), LocalDateTime.now());
            log.info("\n");
        }
    }


}
